package com.heny.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.heny.demo.dbutils.DynamicTableContext;
import com.heny.demo.dbutils.DynamicTableModel;
import com.heny.demo.dbutils.DynamicTableProcessorEnum;
import com.heny.demo.entity.DeviceHistoryData;
import com.heny.demo.mapper.DeviceHistoryDataMapper;
import com.heny.demo.service.DeviceHistoryDataService;
import com.heny.demo.utils.DateTimeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author litao.cc
 * @version DeviceHistoryDataServiceImpl.java v0.1 t2025/5/5 22:17
 * @date 2025/5/5 22:17
 * @description DeviceHistoryDataServiceimpl
 */
@Service
public class DeviceHistoryDataServiceImpl  implements DeviceHistoryDataService {

    @Autowired
    DeviceHistoryDataMapper deviceHistoryDataMapper;
    @Override
    public void add(DeviceHistoryData data,int typeId) {
        Date syncTime = data.getSyncTime();
        LocalDateTime dateTime = DateTimeUtils.convert(syncTime);
        DynamicTableContext.setTableName(DynamicTableProcessorEnum.DEVICE_HISTORY_DATA,new DynamicTableModel(typeId,dateTime.getYear(),dateTime.getMonth().getValue(),dateTime.getDayOfMonth(),dateTime.getHour()));
        deviceHistoryDataMapper.insert(data);
    }

    @Override
    public void addList(List<DeviceHistoryData> dataList,int typeId,int y,int m,int d,int h) {
        DynamicTableContext.setTableName(DynamicTableProcessorEnum.DEVICE_HISTORY_DATA,new DynamicTableModel(typeId,y,m,d,h));
        deviceHistoryDataMapper.addList(dataList);
    }

    @Override
    public List<DeviceHistoryData>  getHDataBySns(List<String> sns,int typeId, int y, int m, int d, int h) {
        DynamicTableContext.setTableName(DynamicTableProcessorEnum.DEVICE_HISTORY_DATA,new DynamicTableModel(typeId,y,m,d,h));

        // 构造开始时间
        Calendar calendar = Calendar.getInstance();
        calendar.set(y, m - 1, d, h, 0, 0);  // 注意：Calendar 的月份从 0 开始
        Date startTime = calendar.getTime();

        // 结束时间 = 开始时间 + 1 小时
        calendar.add(Calendar.HOUR_OF_DAY, 1);
        Date endTime = calendar.getTime();

        return deviceHistoryDataMapper.selectList(new LambdaQueryWrapper<DeviceHistoryData>()
                .in(DeviceHistoryData::getSn, sns)
                .ge(DeviceHistoryData::getSyncTime, startTime)
                .lt(DeviceHistoryData::getSyncTime, endTime));

    }
}
